<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>拼图</title>
        <style>
            #box{
                width: 500px;
                height: 500px;
                position: relative;
            }
            #box img{
                width: 100%;
                height: 100%;
            }
            #box .item{
                background-image: url("./img.jpg");
                transition: all 0.5s;
            }
            #box .item,#box .empty{
                position: absolute;
                width: 100px;
                height: 100px;
            }
            #box .empty{
                background-color: aliceblue;
                transition: all 0.5s;
                z-index: -1;
            }
        </style>
    </head>
    <body>
        <input type="text" id="num" value="5" placeholder="请输入拼图的列数">
        <div id="box">
            <img src="./img.jpg" alt="">
        </div>
        <button id="reload">刷新</button>
    </body>
</html>
<script>
    var box = document.getElementById("box");

    // 布局页面
    function render(){
        // 获取拼图的num值
        var num = document.getElementById("num").value * 1;
        // 修改box的宽高
        box.style.width = num * 100 + "px";
        box.style.height = num * 100 + "px";
        // 25张图的背景位置
        var bgiPos = [];
        for (var i = 0; i < num; i++) {
            for (var j = 0; j < num; j++) {
                bgiPos.push({
                    x: -100 * j + "px",
                    y: -100 * i + "px"
                });
            }
        }
        // 清空内容
        box.innerHTML = "";

        for(var i = 0; i < num*num; i++){
            var div = document.createElement("div"); 
            div.style.top = 100*(Math.floor(i / num)) + "px";
            div.style.left = i % num *100 + "px"; 
            box.appendChild(div);
            // 获取随机索引
            var index = Math.floor(Math.random() * bgiPos.length);
            var pos = bgiPos[index];
            div.style.backgroundPositionX = pos.x;
            div.style.backgroundPositionY = pos.y;
            div.style.backgroundSize = num*100 + "% " + num * 100 + "%";
            // 为了防止重复取值
            bgiPos.splice(index,1);
            // 判断空白位置
            if (pos.x == (-100 * (num - 1) + "px") && pos.y == (-100 * (num - 1) + "px")) {
                div.className = "empty";
            }else{
                div.className = "item";
            }
        }
    }
    document.getElementById("reload").onclick = render;


    // 点击小图片进行移动
    // 注意：这里需要使用事件代理（委托），因为我们界面是点击了刷新才开始布局的，如果一上来就给item添加事件，是添加不上
    box.onclick = function(e){
        var empty = document.getElementsByClassName("empty")[0];
        // 给谁绑定事件
        // console.log(this);
        // console.log(empty.style.left);
        // console.log(e.target.style.left);
        if (e.target.className == "item") {
            // 判断空白在当前点击div的上下
            if (empty.style.left == e.target.style.left) {
                // 在上，还是在下
                if (parseInt(empty.style.top)-100 == parseInt(e.target.style.top)) {
                    // alert("上");
                    empty.style.top = parseInt(empty.style.top) - 100 + "px";
                    e.target.style.top = parseInt(e.target.style.top) + 100 + "px";
                } else if(parseInt(empty.style.top) + 100 == parseInt(e.target.style.top)) {
                    // alert("下");
                    empty.style.top = parseInt(empty.style.top) + 100 + "px";
                    e.target.style.top = parseInt(e.target.style.top) - 100 + "px";
                }
            }
            if (empty.style.top == e.target.style.top) {
                // 在左，还是在右
                if (parseInt(empty.style.left) - 100 == parseInt(e.target.style.left)) {
                    // alert("左");
                    empty.style.left = parseInt(empty.style.left) - 100 + "px";
                    e.target.style.left = parseInt(e.target.style.left) + 100 + "px";
                } else if (parseInt(empty.style.left) + 100 == parseInt(e.target.style.left)) {
                    // alert("右");
                    empty.style.left = parseInt(empty.style.left) + 100 + "px";
                    e.target.style.left = parseInt(e.target.style.left) - 100 + "px";
                }
            }
            isSuccess(document.querySelectorAll(".item"));
        }
    }

    // 封装方法：判断是否拼成
    function isSuccess(divs){
        divs = Array.from(divs);
        var flag = divs.every(function(div){
            return -parseInt(div.style.top) == parseInt(div.style.backgroundPositionY) && -parseInt(div.style.left) == parseInt(div.style.backgroundPositionX);
        });
        if (flag) {
            alert("拼图成功");
        } 
    }

</script>